package com.tbsoft.ehr.dao.common;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.tbsoft.ehr.dao.BaseDaoImpl;
import com.tbsoft.ehr.model.WorkDay;

/**
 * @desc
 * @author vastdream
 * 
 */
public class WorkdayDaoImpl extends BaseDaoImpl<WorkDay> implements WorkdayDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<WorkDay> getDays(final String dateStart, final String dateEnd) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Criteria criteria = session.createCriteria(WorkDay.class);
				criteria.add(Restrictions.between("date", dateStart, dateEnd));
				return criteria.list();
			}
		});
	}

	@Override
	public WorkDay getWorkDayByDate(String date) {
		return (WorkDay) getHibernateTemplate().get(WorkDay.class, date);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<WorkDay> getDaysByYear(final String year) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Criteria criteria = session.createCriteria(WorkDay.class);
				criteria.add(Restrictions.like("date", year, MatchMode.START));
				return criteria.list();
			}
		});
	}
	@Override
	public void deleteDaysByYear(final String year) {
		getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				String hql = "delete WorkDay as wd where wd.date like ?";
				Query query = session.createQuery(hql);
				query.setString(0, year+"%");
				query.executeUpdate();
				return null;
			}
		});
	}

}
